﻿namespace EasyGo.Controllers
{
    using System;
    using System.Linq;
    using System.Threading;
    using System.Web.Mvc;
    using EasyGo.Common.Auth;
    using EasyGo.Common.Commands;
    using EasyGo.Common.Queries;
    using EasyGo.Logic;
    using EasyGo.Models;
    using EasyGo.Utils;

    public class UsersController : EasyGoJsonController
    {
        private readonly IUserQueries userQueries;

        private readonly IUsersManager usersManager;

        public UsersController(IUserQueries userQueries, IUsersManager usersManager)
        {
            this.userQueries = userQueries;
            this.usersManager = usersManager;
        }

        public virtual ActionResult GetAll()
        {
            var response = new JsonResponse(true, this.userQueries.GetAllUsers());
            return response.ToActionResult();
        }

        public virtual ActionResult Find(int id)
        {
            var response = new JsonResponse();
            var user = this.userQueries.FindUser(id);
            if (user != null)
            {
                response.Response = user;
            }
            else
            {
                response.Fail("User not found");
            }

            return response.ToActionResult();
        }
        
        [HttpPost]
        public virtual ActionResult Add(EditUserCommand command)
        {
            var response = new JsonResponse(true);
            this.usersManager.CreateUser(command);
            return response.ToActionResult();
        }

        [HttpPost]
        public virtual ActionResult Modify(EditUserCommand command)
        {
            var response = new JsonResponse(true);
            this.usersManager.EditUser(command);
            return response.ToActionResult();
        }

        [HttpPost]
        public virtual ActionResult Delete(int id)
        {
            var response = new JsonResponse(true);
            this.usersManager.DeleteUser(id);
            return response.ToActionResult();
        }

        [HttpGet]
        public ActionResult GetRoles(string term)
        {
            var response = new JsonResponse(true, UserRole.All.Select(x => new { Id = x.Key, Text = x.Description }));
            return response.ToActionResult();
        }
    }
}
